<template>
  <div style="padding:10px 20px">
    <div class="title-view">编辑地块</div>
    <el-form :model="eidtForm" :rules="rules" ref="refEidtForm" :inline="true" :label-position="'top'">
      <el-form-item label="地块名称" prop="farmLandName">
        <el-input v-model="eidtForm.farmLandName" clearable placeholder="地块名称" style="width:260px;"></el-input>
      </el-form-item>
      <el-form-item label="地块分组" prop="landGroupId"> 
        <el-select v-model="eidtForm.landGroupId" style="width:240px;" placeholder="地块分组">
          <el-option 
                v-for="item in landGroup"
                :key="item.landGroupId"
                :label="item.groupName"
                :value="item.landGroupId">
              </el-option>
        </el-select>
        <i class="vxe-icon-add btn-add-round" @click="btnAdd(1,'分组')"></i>
      </el-form-item>
      <el-form-item label="地块面积" prop="mapAreaSize">
        {{ Number(eidtForm.mapAreaSize||0).toFixed(2) }} (亩)
        <!-- <vxe-input v-model="eidtForm.mapAreaSize"  placeholder="地块面积" type="float" min="0" max="9999" style="width:260px;" clearable></vxe-input> -->
      </el-form-item>
      <el-form-item label="地块位置" prop="locationAddress">
        <div style="padding:0 10px;">{{eidtForm.locationAddress}}</div>
      </el-form-item>
      <el-form-item label="土壤类型" prop="landTypeId" :label-position="'left'">
        <el-radio-group v-model="eidtForm.landTypeId">
          <el-radio :label="item.landTypeId"  v-for="item in landType">{{ item.landTypeName }}</el-radio>
        </el-radio-group> 
      </el-form-item>
      <el-form-item label="土壤质地" prop="geologyId">
        <el-select v-model="eidtForm.geologyId" clearable style="width:240px;" placeholder="土壤质地">
           <el-option
                    v-for="item in geologyList"
                    :key="item.geologyId" 
                    :label="item.geologyName"
                    :value="item.geologyId">
                  </el-option>
        </el-select>      
        <!-- <i class="vxe-icon-add btn-add-round"></i> -->
      </el-form-item>
      <el-form-item label="地块权属" prop="landBelongId">
        <el-select v-model="eidtForm.landBelongId" clearable style="width:240px;" placeholder="地块权属">
          <el-option 
                v-for="item in belongList"
                :key="item.landBelongId"
                :label="item.landBelongName"
                :value="item.landBelongId">
              </el-option>
        </el-select>
        <i class="vxe-icon-add btn-add-round" @click="btnAdd(2,'地块权属')"></i>
      </el-form-item>
      <el-form-item label="地块标签" prop="landTagId">
        <el-select v-model="eidtForm.landTagId" multiple  clearable style="width:240px;" placeholder="地块标签">
          <el-option 
                v-for="item in landTagsList"
                :key="item.landTagId"
                :label="item.tagName"
                :value="item.landTagId">
              </el-option>
        </el-select>
        <i class="vxe-icon-add btn-add-round" @click="btnAdd(3,'地块标签')"></i>
      </el-form-item>
    </el-form>
    <div style="margin:10px auto;text-align: center;">
      <el-button type="primary" style="width:100%;height:40px" @click="onSubmit" class="vxe-icon-check">完成</el-button>
    </div>
    <el-button  @click="onClose" class="btn-back vxe-icon-arrow-left">返回</el-button>
    <vxe-modal ref="modalAdd" v-model="modalAddType" :title="'添加'+modalTitle" width="400" @zoom="zoomBox"  resize show-footer>
      <template #default>
        <el-form  :model="form" style="padding-top:10px;">
            <el-form-item :label="modalTitle">
              <el-input :placeholder="'请输入'+modalTitle" clearable v-model="addText"><template #append> <span @click="saveSelect" style="cursor: pointer;">添加</span></template></el-input>
            </el-form-item>
        </el-form>
        <vxe-table
            ref="refTable"
            :border="true"
            :height="tableHeight"
            :row-config="{isHover: true}"
            :column-config="{resizable: true}"
            :scroll-y="{enabled: true}"
            :data="getMinTableList">
            <vxe-column type="seq" title="序号" width="60"></vxe-column>
            <vxe-column field="name" :title="modalTitle+'名称'"></vxe-column>
            <vxe-column field="id" title="操作"  width="85">
              <template #default="{row}">
                <vxe-button type="text" status="danger" @click="btnDel(row)" content="删除" icon="vxe-icon-delete"></vxe-button>
                </template>
            </vxe-column>
        </vxe-table>
      </template>
      <template #footer>
        <el-button class="vxe-icon-close" @click="modalAddType=false">关闭</el-button>
            <el-button type="primary" class="vxe-icon-check" @click="modalAddType=false">保存</el-button>
        </template>
    </vxe-modal>
</div>
</template>

<script setup name="eidtRow">
import { nextTick, ref, watch, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import {VXETable} from 'vxe-table'
import {
  getLandGroupList,
  getLandTypeList,
  getGeologyList,
  getBelongList,
  getLandTagsList,
  addGroup,
  delGroup,
  addLandBelong,
  addLandTags,
  deleteBelong,
  editFarmLand,
  deleteTags,
  getLandNewDetail
} from '@/api/plant'
const userStore = useUserStore()
const modalType =ref(false)
const refEidtForm =ref(null)
const emit = defineEmits(['close'])
const tableHeight=ref('300px')
const props = defineProps({
   farmLandId:{
        type:String,
        default:''
    }
})
const addText =ref('')
const LoadingSave = ref(false)
const modalAddType = ref(false)
const landGroup = ref([])
const landType = ref([])
const geologyList = ref([])
const belongList = ref([])
const landTagsList = ref([])
const minType =ref(1)
const modalTitle =ref('')
const eidtForm = ref({
  farmLandName:'',
  landGroupId:'',
  mapAreaSize:'',
  locationAddress:'',
  landTypeId:'',
  geologyId:'',
  landBelongId:'',
  landTagId:[]
})
const rules= ref({
  farmLandName: [{ required: true, message: '此项必填', trigger: 'blur' }],
  landGroupId: [{ required: true, message: '此项必填', trigger: 'blur' }],
  mapAreaSize: [{ required: true, message: '此项必填', trigger: 'blur' }],
  locationAddress: [{ required: true, message: '此项必填', trigger: 'blur' }],
  landTypeId: [{ required: true, message: '此项必填', trigger: 'blur' }],
  // geologyId: [{ required: true, message: '此项必填', trigger: 'blur' }],
  // landBelongId: [{ required: true, message: '此项必填', trigger: 'blur' }],
  // landTagId: [{ required: true, message: '此项必填', trigger: 'blur' }]
})

const minTableData = ref([])
const getMinTableList =computed(()=>{
  if(minType.value==1){
    return  minTableData.value = landGroup.value.map((item)=>{
        return {
          id:item.landGroupId,
          name:item.groupName
        }
      })
  }

  if(minType.value==2){ 
    return minTableData.value = belongList.value.map((item)=>{
        return {
          id:item.landBelongId,
          name:item.landBelongName
        }  
      })
  }  
  if(minType.value==3){
    return  minTableData.value = landTagsList.value.map((item)=>{
        return {
          id:item.landTagId,
          name:item.tagName
        }
      })
  }
})
  onMounted(() => {
      getLandGroup()
      getLandType()
      getGeology()
      getBelong()
      getLandTags()
      getLandInfo()
  })

watch(()=>props.farmLandId,(n,o)=>{
    getLandInfo()
})
  const getLandInfo=()=>{
    getLandNewDetail({farmLandId:props.farmLandId}).then((res)=>{
          if(res.success){
            eidtForm.value = res.data ||{}
            if(res.data.landTagIds){
              eidtForm.value.landTagId=res.data.landTagIds.split(',').map((item)=>Number(item))
            }
          }
      })
  }
  const btnAdd=(type,title)=>{
    modalAddType.value = true
    modalTitle.value = title
    minType.value = type
   }
  //分组
  const getLandGroup =async ()=>{
    let res  = await  getLandGroupList({
       page: 1, 
       limit: 100,
       farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId
    })
    if(res.success){
      landGroup.value = res.data ||[]
    }
  }
  //类型
  const getLandType =async ()=>{
    let res  = await  getLandTypeList({page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
      landType.value = res.data ||[]
    }
  }
  //土壤地质
  const getGeology =async ()=>{
    let res  = await  getGeologyList({ page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
        geologyList.value = res.data ||[]
    }
  }
    //地块权属
    const getBelong =async ()=>{
    let res  = await  getBelongList({ page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
      belongList.value = res.data ||[]
    }
  }

    //地块标签
    const getLandTags =async ()=>{
    let res  = await  getLandTagsList({ page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
      landTagsList.value = res.data ||[]
    }
  }

const onSubmit=async ()=>{
  refEidtForm.value.validate(async(valid) => {
      if (valid) {
        LoadingSave.value = true
        let res = await editFarmLand({
          farmLandId:eidtForm.value.farmLandId,
          farmLandName:eidtForm.value.farmLandName,
          landGroupId:eidtForm.value.landGroupId,
          landTypeId:eidtForm.value.landTypeId,
          geologyId:eidtForm.value.geologyId,
          landBelongId:eidtForm.value.landBelongId,
          landTagIds:eidtForm.value.landTagId,
          groupName:landGroup.value.find((item)=>eidtForm.value.landGroupId==item.landGroupId)?.groupName||null,
          geologyName:geologyList.value.find((item)=>eidtForm.value.geologyId==item.geologyId)?.geologyName||null,
          landBelong:belongList.value.find((item)=>eidtForm.value.landBelongId==item.landBelongId)?.landBelongName||null,
        })
        if(res.success){
            LoadingSave.value = false
            VXETable.modal.message({ content: '保存成功', status: 'success'})
            onClose()
          }else{
            LoadingSave.value = false
            VXETable.modal.message({ content: res.message, status: 'error'})
          }

          }
  });
}

const saveSelect=async ()=>{
  if(!addText.value){
    VXETable.modal.message({ content: '名称不能为空', status: 'error'})
    return 
  }
  let res =minType.value==1?await addGroup({farmId:userStore.userInfo.farmId,groupName:addText.value}):
  (
    minType.value==2?await addLandBelong({companyId:userStore.userInfo.companyId,landBelongName:addText.value}):
    await addLandTags({companyId:userStore.userInfo.companyId,tagName:addText.value})
  )
  if(res.success){
      VXETable.modal.message({ content: '新增成功', status: 'success'})
      addText.value=''
      if(minType.value==1){
        getLandGroup()
      }else if(minType.value==2){
        getBelong()
      }else{
        getLandTags()
      }
     
    }else{
      VXETable.modal.message({ content: res.message, status: 'error'})
    }
}

const btnDel=async (row)=>{
  const info = await VXETable.modal.confirm({
        title:'提示',
        content:'您确定要删除该数据?'
    })
    if(info==='confirm'){
      let res = minType.value==1?await delGroup([row.id]):(minType.value==2?await deleteBelong([row.id]):await deleteTags([row.id])) 
        if(res.success){
          VXETable.modal.message({ content: '删除成功', status: 'success'})
          if(minType.value==1){
               getLandGroup()
            }else if(minType.value==2){
               getBelong()
            }else{
              getLandTags()
            }
        }else{
          VXETable.modal.message({ content: res.message, status: 'error'})
        }
    }
}
const onClose = ()=>{
    emit('close')
}

</script>

<style lang="scss" scoped>
.title-view{
   height:30px;
   font-size:16px;
   color: #333;
   border-bottom:1px solid #ddd;
   margin-bottom:20px;
   position: relative;
   text-indent:6px;
   &::after{
    position: absolute;
    height:18px;
    width:3px;
    content: '';
    background-color: #04AE70;
    left: 0;
   }
}
.btn-add-round{
  cursor: pointer;
  position: absolute;
  right:-30px;
  border-radius:20px;
  border:1px solid #04AE70;
  color: #04AE70;
  font-size:13px;
  padding:2px;
}
.btn-back{
  position: fixed;
    right: 20px;
    top: 80px;
    z-index: 99;
    cursor: pointer;
}
</style>
